package categoryvalidator

import (
	"fmt"
	"time"
	"yunj/app/model"
	"yunj/pkg/global"
	"yunj/pkg/yunj/util"

	"github.com/worklz/go-validate"
	"gorm.io/gorm"
)

type Category struct {
	validate.Validator
}

func (v *Category) HandleDatas(datas map[string]interface{}, scene string) (err error) {
	if scene == "FormSubmit" {
		err = v.HandleDatasByFormSubmit(datas)
		if err != nil {
			return
		}
	}
	return
}

func (v *Category) HandleDatasByFormSubmit(datas map[string]interface{}) (err error) {
	currTime := time.Now().In(time.Local)
	dbCategory := &model.Category{
		Name: util.MapKeyValue(datas, "name", ""),
		Img:  util.MapKeyValue(datas, "img", ""),
		Desc: util.MapKeyValue(datas, "desc", ""),
	}
	// last_update_time
	dbCategory.LastUpdateTime = currTime.Unix()
	// id
	var id uint64
	if idRaw, exists := datas["id"]; exists {
		var idVal uint64
		if idVal, err = util.ToUint64(idRaw); err == nil && idVal > 0 {
			id = idVal
		}
	}
	dbCategory.Id = id
	// alias
	alias := util.MapKeyValue(datas, "alias", "")
	if alias != "" {
		var existsCategory model.Category
		dbErr := global.MySQL.Where("id <> ? and alias = ?", id, alias).First(&existsCategory).Error
		if dbErr != nil && dbErr != gorm.ErrRecordNotFound {
			err = fmt.Errorf("判断别名是否存在数据获取异常！%v", dbErr)
			return
		}
		if existsCategory.Id > 0 {
			err = fmt.Errorf("别名已存在！与分类“%s”冲突", existsCategory.Name)
			return
		}
		dbCategory.Alias = alias
	}
	datas["dbCategory"] = dbCategory
	return
}
